/*
 * @Description: 线索
 * @Author: Zzt
 * @Date: 2022-08-23 09:59:34
 * @LastEditTime: 2023-03-03 10:48:49
 */

import { fetchATListByFondId } from '@/api/archivesType';
import { fetchFondsListByUnitId } from '@/api/fonds';
import { IArchiveType } from '@/interfaces/archiveType';
import { IFond } from '@/interfaces/fond';
import { appState } from '@/store/mobx';
import { Checkbox, Form, Input, Space, Tabs } from 'antd';
import { debounce } from 'lodash-es';
import classNames from 'classnames/bind';
import { useEffect, useState } from 'react';
import Limit from './styles/SearchLimit.module.scss';
import { observer } from 'mobx-react-lite';
import { CheckCircleFilled } from '@ant-design/icons';
import { selectItemByKey } from '@/utils/list';

const { TabPane } = Tabs;
const cx = classNames.bind(Limit);

const forms = [
  { label: '年度', key: 1, name: 'year' },
  { label: '密级', key: 2, name: 'classification' }
];

interface IClueProps {
  onChange: any;
  type: string;
  param?: any;
  conditions?: any;
}
/* 
这是头部
*/
const SearchLimit = (props: IClueProps) => {
  const [form] = Form.useForm();
  const { onChange, type, param, conditions } = props;
  console.log(param);
  // 全宗列表
  const [fondsList, setFondsList] = useState<IFond[]>([]);
  // 档案类型列表
  const [ATList, setATList] = useState<IArchiveType[]>([]);
  // 选中的全宗
  const [selectFondId, setSelectFondId] = useState(0);
  // 选中的档案类型id
  const [selectATId, setSelectATId] = useState([]);

  const [atConditionList, setAtConditionList] = useState([]);

  const [defaultSelection, setDefaultSelection] = useState<any>({});

  // 字段条件列表
  const [fieldConditionList, setFieldConditionList] = useState([]);

  /**
   * @description:根据id插入条件
   * @param {number} id 更新项目id
   * @param {Object} data 插入的数据
   * @param {Array<Object>} list 原表格数据列表
   * @param {string} key 对应字段
   * @return {Array<Object>} 处理后的表格数据列表
   */
  function updateSearchById(id: any, data: any, list: any, key = 'fondId') {
    if (list.length === 0) {
      list.push(data);
    } else {
      for (let i = 0; i < list.length; i++) {
        if (list[i][key] === id) {
          list.splice(i, 1, { ...list[i], ...data });
        } else {
          list.push(data);
        }
      }
    }
    return list.map((item: any) => item);
  }
  // 加载时获取全宗列表，获取成功后默认选中第一条并把第一条返回出去
  useEffect(() => {
    const { unitId } = appState;
    if (unitId) {
      fetchFondsListByUnitId(unitId).then((res) => {
        if (!param) {
          const _fondList: IFond[] = res.data;
          setFondsList(_fondList);
          setSelectFondId(_fondList[0]?.id);
        } else {
          const _fondList: IFond[] = res.data;
          setFondsList(_fondList);
          setSelectFondId(param[0].fondId);
        }
      });
    }
  }, [appState.unitId]);

  // 切换全宗自动加载档案类型
  useEffect(() => {
    if (selectFondId) {
      fetchATListByFondId(selectFondId).then((res) => {
        if (!param) {
          /* param没有值的时候执行（起始检索页） */
          setDefaultSelection(conditions.find((item: any) => item.fondId === selectFondId));
          const _atList: IArchiveType[] = res.data;
          setATList(_atList);
          if (!defaultSelection) return;
          setSelectATId(defaultSelection.archiveTypeIdList);
        } else {
          /* param有值的时候执行（内部额外检索） */
          const dataSelect = param.find((item: any) => item.fondId === selectFondId);
          const noHaveData = param.some((item: any) => item.fondId === selectFondId);
          const _atList: IArchiveType[] = res.data;
          setATList(_atList);
          if (!noHaveData) return;
          setSelectATId(dataSelect.archiveTypeIdList);
        }
      });
    }
  }, [selectFondId]);

  useEffect(() => {
    if (param) {
      setAtConditionList(param);
    }
    if (selectATId) {
      onChange({ atConditionList, fieldConditionList });
    }
  }, [selectATId, fieldConditionList]);
  /**
   * @description: 切换全宗
   * @param {number} val 选中的全宗
   */
  const handleFondChange = (val: any) => {
    setSelectFondId(parseInt(val, 10));
  };

  /**
   * @description: 切换档案类型
   * @param {any} param1
   */
  const onATSelect = (value: any) => {
    console.log('onATSelect', atConditionList);
    setSelectATId(value);
    const condition = { fondId: selectFondId, archiveTypeIdList: value };
    setAtConditionList(updateSearchById(selectFondId, condition, atConditionList));
  };

  // // 档案类型列表item
  // const items = ATList.map((item: IArchiveType) => ({ label: item.atName, value: item.id }));
  // /* 字段值更新触发 */
  // const onValuesChange = debounce(() => {
  //   form.submit();
  // }, 300);

  // const onFinish = (file: any) => {
  //   setFieldConditionList([file]);
  // };

  const showFondCheck = (fondId: number) => {
    const fondObj = selectItemByKey(fondId, atConditionList, 'fondId');
    console.log('fondObj', fondObj);
    return !!(fondObj && fondObj?.archiveTypeIdList.length > 0);
  };

  return (
    <div className={cx('out')}>
      <div className={cx('in1')}>
        <p>限定全宗</p>
        <Tabs tabPosition="left" className={cx('tab')} onTabClick={handleFondChange}>
          {fondsList.map((fond) => (
            <TabPane
              tab={
                <>
                  {showFondCheck(fond.id) && <CheckCircleFilled className={cx('fond-checked')} />}
                  {fond.fondName}
                </>
              }
              key={fond.id}
            >
              <div>
                <p>限定档案类型</p>
                <div className={cx('check')}>
                  <Checkbox.Group
                    onChange={onATSelect}
                    className={cx('checkbox')}
                    value={selectATId}
                  >
                    <Space direction="vertical">
                      {ATList.map((item) => (
                        <Checkbox value={item.id} key={item.id}>
                          {item.atName}
                        </Checkbox>
                      ))}
                    </Space>
                  </Checkbox.Group>
                </div>
              </div>
            </TabPane>
          ))}
        </Tabs>
      </div>
      {/* <div className={cx('in2')}>
        <Form
          labelCol={{ span: 7 }}
          wrapperCol={{ span: 16 }}
          form={form}
          onFinish={onFinish}
          onValuesChange={onValuesChange}
        >
          <p>条件限定</p>
          <div className={cx('forms')}>
            {forms.map((form) => (
              <Form.Item label={form.label} key={form.key} name={form.name}>
                <Input placeholder={`请填写${form.label}`}></Input>
              </Form.Item>
            ))}
          </div>
        </Form>
      </div> */}
    </div>
  );
};
export default observer(SearchLimit);
